package com.exercises;

import java.util.HashMap;
import java.util.Map;

class Exercise525 {
    public static void main(String[] args) {
        System.out.println(findMaxLength(new int[]{0, 1, 0, 1, 1, 0}));

    }

    public static int findMaxLength(int[] nums) {
        int length = nums.length;
        int[] sum = new int[length];
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int result = 0;
        for (int i = 0; i < length; i++) {
            nums[i] = nums[i] == 0 ? -1 : 1;
            if (i == 0) sum[i] = nums[i];
            else sum[i] = sum[i - 1] + nums[i];
            int key = sum[i];
            if (map.containsKey(key)) {
                int j = map.get(key);
                result = Math.max(result, i - j);
            } else {
                map.put(key, i);
            }
        }
        return result;
    }

}
